package com.hqx.gulimall.product.exception;

import com.hqx.common.exception.GulimallCodeEnum;
import com.hqx.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.hqx.gulimall.product.controller")
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("异常信息:{}",e.getMessage());
        Map<String,String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((item) -> map.put(item.getField(),item.getDefaultMessage()));
        return R.error(GulimallCodeEnum.VALID_EXCEPTION.getCode(),GulimallCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("异常信息:{}",throwable.getMessage());
        return R.error(GulimallCodeEnum.UNKNOWN_EXCEPTION.getCode(),GulimallCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
